package com.fieldchain.ex.fa100.utils.net.modle;

import com.fieldchain.ex.fa100.bean.event.BaseEvent;
import com.fieldchain.ex.fa100.utils.net.inter.BaseRequest;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;

/**
 * Created by biyunlong on 2017/5/3.
 * Make progress every day
 */

public abstract class BeanRequestTwo<T> extends BaseRequest {
    private int status=0;
    private String msg;

    @Override
    public void baseOnSucess(String jsonstr,String tags) {
        try {
            JSONObject jsonRoot = new JSONObject(jsonstr);
            status=jsonRoot.getInt("code");
            msg=jsonRoot.getString("msg");
            EventBus.getDefault().post(new BaseEvent(status,tags));
            if(status==200) {
                T t = (T) (new Gson().fromJson(jsonstr, ((ParameterizedType) (getClass().getGenericSuperclass())).getActualTypeArguments()[0]));
                onSucess(t, status, msg);
            }else{
                onSucess(null, status, msg);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void baseOnFaild(Exception e,String tags) {
        onFaild(e);
    }

    public abstract void onSucess(T t,int code,String msg);
    public abstract void onFaild(Exception e);
}
